export default class NumberAnimationValue {
  private _value: number
  private targetValue: number
  private maxDisparity: number
  speed: number
  /**
   *
   * @param value 默认值
   * @param speed 变化速度 (0,1]
   */
  constructor(value: number, speed: number = 0.1, maxDisparity = 1000) {
    this._value = value
    this.targetValue = value
    this.maxDisparity = maxDisparity
    this.speed = Math.max(Math.min(1, speed), 0.001)
  }
  update() {
    this.goTo()
    return this.value
  }
  private goTo() {
    if (Math.abs(this.value - this.targetValue) >= this.maxDisparity) {
      this._value = this.targetValue
      return
    }
    this._value = this.lerp(this._value, this.targetValue, this.speed)
  }
  private lerp(a: number, b: number, t: number) {
    if (a == b) {
      return a
    }
    let v = a + (b - a) * t
    if (Math.abs(v - b) < 0.0001) {
      v = b
    }
    return v
  }
  set value(v: number) {
    this.targetValue = v
  }

  get realValue() {
    return this._value
  }
  get value() {
    return this._value
  }
}
